<template>
  <!-- 列表里的操作 -->
  <div class="inline">
    <!-- 下拉 -->
    <el-dropdown>
      <el-link class="ml-2 mt-[5px]" type="primary" :underline="false">
        更多
        <el-icon class="el-icon--right">
          <arrow-down />
        </el-icon>
      </el-link>
      <template #dropdown>
        <el-dropdown-menu>
          <!-- 删除订单 -->
          <el-dropdown-item v-if="deleteBtn">
            <el-link
              v-perms="['order:del']"
              type="danger"
              :underline="false"
              @click="handleDelete"
              >删除订单</el-link
            >
          </el-dropdown-item>

          <el-dropdown-item v-if="cancelBtn">
            <el-link
              v-perms="['order:cancel']"
              type="primary"
              :underline="false"
              @click="handleCancel"
              >取消订单</el-link
            >
          </el-dropdown-item>
          <el-dropdown-item>
            <popup
              class="inline mr-2"
              width="450px"
              :center="true"
              @confirm="handleRemark"
              @open="getRemarkDetail"
            >
              <template #trigger>
                <el-link
                  v-perms="['order:remark']"
                  type="primary"
                  :underline="false"
                  @click="getserviceList()"
                  >包年保姆绑定</el-link
                >
              </template>
              <div style="height: 300px" class="mt-4">
                <el-form
                  ref="orderFormRef"
                  :model="orderForm"
                  label-width="auto"
                >
                  <el-form-item label="服务名称" prop="goodsId">
                    <el-input
                      v-model="orderForm.name"
                      :value="'保姆包年服务'"
                    />
                  </el-form-item>
                  <el-form-item label="保姆列表" prop="name">
                    <el-select
                      v-model="orderForm.staffId"
                      filterable
                      @change="goodschange(serviceList)"
                      placeholder="请选择服务名称"
                      style="width: 100%"
                      @click="getserviceList"
                    >
                      <el-option
                        v-for="item in serviceList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </popup>
          </el-dropdown-item>
          <el-dropdown-item v-if="verificationBtn">
            <el-link
              v-perms="['order:verification']"
              type="primary"
              :underline="false"
              @click="handleVerification(null)"
              >包年预约</el-link
            >
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
  <el-dialog v-model="dialogTableVisible" title="预约" width="800">
    <el-button type="primary" @click="subscribe">点击预约</el-button>
    <el-button type="primary" @click="cancelReservation">取消预约</el-button>
    <el-button type="primary" @click="updateservation">已完成</el-button>
    <el-calendar v-model="calendartime">
      <template #date-cell="{ data }">
        <p :class="data.isSelected ? 'is-selected' : ''">
          {{ data.day.split("-").slice(1).join("-") }}
        </p>
        <div style="padding: 10px; text-align: center">
          <span style="font-size: 22px">
            {{ gettime(data.day.split("-").slice(1).join("-")) }}
          </span>
        </div>
      </template>
    </el-calendar>
  </el-dialog>
  <!-- 详情里的操作 -->
</template>

<script lang="ts" setup>
import {
  apiOrderDel,
  apiOrderVerification,
  apiOrderCancel,
  apiOrderRemark,
  getstaffList,
  postorderBindAnnualService,
  getserviceListapi,
  postserviceadd,
  postservicedel,
  updateservicedel,
} from "@/api/order/lists";
import Popup from "@/components/popup/index.vue";
import { ref, defineEmits } from "vue";
import feedback from "@/utils/feedback";
import { watch } from "vue";
import { DeleteLocation } from "@element-plus/icons-vue";
const emit = defineEmits(["refresh"]);

const props = withDefaults(
  defineProps<{
    id: string | number; //订单ID
    code: number | null; // 核销码
    btnStyle: string; //按钮样式
    cancelBtn: number; //取消订单
    deleteBtn: number; //删除订单
    verificationBtn: number; //核销按钮
    verificationStatus: number; //核销文字
    verificationCode: string | null; // 核销码
    orderRemarks: string; // 商家备注
  }>(),
  {
    id: "",
    btnStyle: "text",
    cancelBtn: 0,
    deleteBtn: 0,
    verificationBtn: 0,
    verificationStatus: 0,
    verificationCode: "",
    orderRemarks: "",
  }
);

const orderForm = ref({
  name: "保姆包年服务" as string,
  orderId: props.id,
  staffId: null,
});

// 取消订单
const handleCancel = async (): Promise<void> => {
  await feedback.confirm("确定要取消订单吗？");
  await apiOrderCancel({ id: props.id });
  feedback.msgSuccess("操作成功");
  emit("refresh");
};

// 包年
const serviceListapiData = ref([]);
const handleVerification = async (time: any): Promise<void> => {
  let currentMonthFirstDay;
  let currentMonthLastDay;
  if (time) {
    currentMonthFirstDay = new Date(time);
    currentMonthFirstDay.setDate(1);
    currentMonthLastDay = new Date(time);
    currentMonthLastDay.setMonth(currentMonthLastDay.getMonth() + 1);
    currentMonthLastDay.setDate(0);
  } else {
    currentMonthFirstDay = new Date();
    currentMonthFirstDay.setDate(1);
    currentMonthLastDay = new Date();
    currentMonthLastDay.setMonth(currentMonthLastDay.getMonth() + 1);
    currentMonthLastDay.setDate(0);
  }
  // 获取当前月的第一天

  // 获取当前月的最后一天

  let res = await getserviceListapi({
    orderId: props.id,
    startDate: dateFormatter("YYYY-MM-DD", currentMonthFirstDay),
    endDate: dateFormatter("YYYY-MM-DD", currentMonthLastDay),
  });
  serviceListapiData.value = res.lists;
  dialogTableVisible.value = true;
};

// 删除服务
const handleDelete = async (): Promise<void> => {
  await feedback.confirm("确认要删除吗？");
  await apiOrderDel({ id: props.id });
  feedback.msgSuccess("操作成功");
  emit("refresh");
};

// 提交绑定保姆
const handleRemark = async () => {
  let res = await postorderBindAnnualService(orderForm.value);
  if (res.code == "200") {
    feedback.msgSuccess("操作成功");
    emit("refresh");
  } else {
    feedback.msgError("操作失败");
  }
};

// 商家备注详情
const getRemarkDetail = async () => {};

const handlebindingc = () => {
  editRef.value?.open("add");
};
const handlebinding = () => {
  console.log(1);
};

const serviceList = ref([]);
const dialogTableVisible = ref(false);
const getserviceList = async () => {
  let res = await getstaffList({ pageNo: 1, pageSize: 999, type: 1 });
  serviceList.value = res.lists;
  console.log(serviceList.value);
};
const getservice = async () => {};

const calendartime = ref();
//预算
const subscribe = async () => {
  await postserviceadd({
    orderId: props.id,
    date: dateFormatter("YYYY-MM-DD", calendartime.value),
  }).then(() => {
      feedback.msgSuccess("操作成功");
  });
  handleVerification(null);
};

//取消预约
const cancelReservation = () => {
  let tid;
  serviceListapiData.value.forEach((e: any, i: any) => {
    if (
      dateFormatter("MM-DD", e.date) ==
      dateFormatter("MM-DD", calendartime.value)
    ) {
      tid = e.id;
    }
  });

  let res = postservicedel({
    id: tid,
    date: dateFormatter("YYYY-MM-DD", calendartime.value),
  });
  if (res.code == "200" || res.code == 200 || res != []) {
    feedback.msgSuccess("操作成功");
  } else {
    feedback.msgError("操作失败");
  }
  handleVerification(null);
};
const updateservation = () => {
  let tid;
  serviceListapiData.value.forEach((e: any, i: any) => {
    if (
      dateFormatter("MM-DD", e.date) ==
      dateFormatter("MM-DD", calendartime.value)
    ) {
      tid = e.id;
    }
  });

  let res = updateservicedel({
    id: tid,
    date: dateFormatter("YYYY-MM-DD", calendartime.value),
    status: "1",
  });
  console.log(res);
  if (res.code == "200" || res.code == 200 || res != []) {
    feedback.msgSuccess("操作成功");
  } else {
    feedback.msgError("操作失败");
  }
  handleVerification(null);
};
const dateFormatter = (formatter: any, date: any) => {
  date = date ? new Date(date) : new Date();
  const Y = date.getFullYear() + "",
    M = date.getMonth() + 1,
    D = date.getDate(),
    H = date.getHours(),
    m = date.getMinutes(),
    s = date.getSeconds();
  return formatter
    .replace(/YYYY|yyyy/g, Y)
    .replace(/YY|yy/g, Y.substr(2, 2))
    .replace(/MM/g, (M < 10 ? "0" : "") + M)
    .replace(/DD/g, (D < 10 ? "0" : "") + D)
    .replace(/HH|hh/g, (H < 10 ? "0" : "") + H)
    .replace(/mm/g, (m < 10 ? "0" : "") + m)
    .replace(/ss/g, (s < 10 ? "0" : "") + s);
};
const gettime = (time: any) => {
  let ret;
  serviceListapiData.value.forEach((e: any, i: any) => {
    if (dateFormatter("MM-DD", e.date) == time) {
      ret = e.status == "0" ? "约" : "包";
    }
  });
  return ret;
};
watch(
  () => calendartime.value,
  (newValue, oldValue) => {
    // 在值发生变化时执行的回调函数
    // newValue为新的值，oldValue为旧的值
    // 可以在这里进行相应的处理逻辑
    handleVerification(newValue);
  }
);
onMounted(() => {});
</script>

<style lang="scss" scoped>
.ls-input {
  width: 30vw;
}
.is-selected {
  color: #1989fa;
}
</style>
